﻿Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports GuildCMS.Common

Namespace Account
    Public Class Resend
        Inherits System.Web.UI.Page

#Region " Database variables "

        ''' <summary>
        ''' Set the database connection variables used throughout this class.
        ''' </summary>
        ''' <remarks>Placed here so they will not need to be typed out each time they are needed.</remarks>
        Private connectionString As String = WebConfigurationManager.ConnectionStrings("SqlConnectionString").ConnectionString()
        Private connection As SqlConnection = New SqlConnection(connectionString)
        Private command As New SqlCommand

#End Region

        ''' <summary>
        ''' Handles the Load event of the Page control.
        ''' </summary>
        ''' <param name="sender">The source of the event.</param>
        ''' <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            ' Check if member's account has already been activated.
            If CheckActive(Session("MemberId")) = False Then
                ' Set variables used to send the activation e-mail.
                Dim subject As String = CStr(GetSetting("EmailSubjectRegister"))

                Dim exOccured As Boolean = False

                ' If the member's account has not been activated get the registered members email address.
                Dim memberEmail As String = Nothing
                Try
                    command = New SqlCommand("sp_public_getMemberEmail", connection)
                    command.CommandType = CommandType.StoredProcedure
                    command.Parameters.Add("@MemberId", SqlDbType.NVarChar, 50)
                    command.Parameters("@MemberId").Value = "EmailServer"
                    command.Parameters.Add("@MemberEmail", SqlDbType.NVarChar, 100)
                    command.Parameters("@MemberEmail").Direction = ParameterDirection.Output
                    connection.Open()
                    command.ExecuteNonQuery()
                    memberEmail = CStr(command.Parameters("@MemberEmail").Value)
                Catch ex As Exception
                    exOccured = True
                Finally
                    connection.Close()
                End Try

                ' Generate a new activation code.
                Dim activationCode As String = MakeRandomString(10)

                ' Generate the e-mail message body.
                Dim body As String = GenerateBody(memberEmail, activationCode)

                ' Check if an exception was thrown or not.
                If exOccured = False Then
                    ' Send the activation e-mail.
                    SendMail(memberEmail, subject, body)
                    panSuccess.Visible = True
                    panFailed.Visible = False
                    panActivated.Visible = False
                Else
                    ' If an exception was thrown show an error message.
                    panSuccess.Visible = False
                    panFailed.Visible = True
                    panActivated.Visible = False
                End If
            Else
                panSuccess.Visible = False
                panFailed.Visible = False
                panActivated.Visible = True
            End If
        End Sub

        ''' <summary>
        ''' Checks if a member's account is marked as activated or not activated.
        ''' </summary>
        ''' <param name="memberId">The member's id number.</param>
        ''' <returns>True or false if the account is activated or not.</returns>
        Private Function CheckActive(ByVal memberId As Integer) As Boolean
            Try
                command = New SqlCommand("sp_public_checkActiveAccount", connection)
                command.CommandType = CommandType.StoredProcedure
                command.Parameters.Add("@Member_Id", SqlDbType.Int)
                command.Parameters("@Member_Id").Value = memberId
                command.Parameters.Add("@Active", SqlDbType.Bit)
                command.Parameters("@Active").Direction = ParameterDirection.Output
                connection.Open()
                command.ExecuteNonQuery()
                ' If the member's account is not activated return false.
                If CBool(command.Parameters("@Active").Value) = False Then
                    Return False
                End If
            Catch ex As Exception
                ' If an exception occurs return false.
                Return False
            Finally
                connection.Close()
            End Try
            ' If the member's account is marked active return true.
            Return True
        End Function

#Region " Data generation specific functions. "

        ''' <summary>
        ''' Generates a random activation code.
        ''' </summary>
        ''' <param name="size">The length we want the string to be.</param>
        ''' <returns>Returns the randomly generated activation code user to activate the new account.</returns>
        Private Function MakeRandomString(ByVal size As Integer) As String
            Dim rand As New Random()
            ' Characters we will use to generate this random string.
            Dim allowableChars() As Char = "ABCDEFGHIJKLOMNOPQRSTUVWXYZ0123456789".ToCharArray()

            ' Start generating the random string.
            Dim activationCode As String = String.Empty
            For i As Integer = 0 To size - 1
                activationCode += allowableChars(rand.Next(allowableChars.Length - 1))
            Next

            ' Return the random string in upper case.
            Return activationCode.ToUpper()
        End Function

#End Region

#Region " Activation e-mail specific functions and procedures. "

        ''' <summary>
        ''' Generates the body of the activation e-mail message.
        ''' </summary>
        ''' <param name="email">The email address supplied by the registrant.</param>
        ''' <param name="code">The activation code generated earlier.</param>
        ''' <returns>The body of the registration activation e-mail.</returns>
        Private Function GenerateBody(ByVal email As String, ByVal code As String) As String
            ' Retreive activation e-mail body template from the database.
            Dim body As String = CStr(GetSetting("EmailBodyRegister"))

            ' Retreive server site settings used in the construction of the activation url string.
            Dim serverProtocol As String = CStr(GetSetting("ServerProtocol"))
            Dim serverDomain As String = CStr(GetSetting("ServerDomain"))
            Dim serverPort As String = CStr(GetSetting("ServerPort"))
            Dim serverPath As String = CStr(GetSetting("ServerPath"))

            ' If the protocol is set to http and the port is 80 set port variable to nothing.
            If serverProtocol = "http://" And serverPort = "80" Then
                serverPort = Nothing
            End If

            ' If the protocol is set to https and the port is 443 set the port variable to nothing.
            If serverProtocol = "https://" And serverPort = "443" Then
                serverPort = Nothing
            End If

            ' Replace special strings with dynamically generated ones.
            body = body.Replace("[[CODE]]", code)
            body = body.Replace("[[ACTIVATIONURL]]", serverProtocol & serverDomain & serverPath & "Account/Activate.aspx?email=" & email & "&code=" & code)

            ' Return the message body.
            Return body
        End Function

#End Region

    End Class
End Namespace